<?php
namespace Topxia\WebBundle\Controller;

use Topxia\Common\SmsToolkit;
use Topxia\Common\ArrayToolkit;
use Symfony\Component\HttpFoundation\Request;
use Topxia\Service\Order\OrderProcessor\OrderProcessorFactory;

class OrderController extends BaseController
{
    public function showAction(Request $request)
    {
        $currentUser = $this->getCurrentUser();
        if (!$currentUser->isLogin()) {
            return $this->redirect($this->generateUrl('login'));
        }
		
        $targetType = $request->query->get('targetType');
        $targetId   = $request->query->get('targetId');

        if (empty($targetType) || empty($targetId) || !in_array($targetType, array("course", "vip", "classroom"))) {
            return $this->createMessageResponse('error', '参数不正确');
        }

        if ($targetType == 'classroom') {
            $classroom = $this->getClassroomService()->getClassroom($targetId);

            if (!$classroom['buyable']) {
                return $this->createMessageResponse('error', "该{$classroomSetting['name']}不可购买，如有需要，请联系客服");
            }
        }

        $processor = OrderProcessorFactory::create($targetType);
        $checkInfo = $processor->preCheck($targetId, $currentUser['id']);

        if (isset($checkInfo['error'])) {
            return $this->createMessageResponse('error', $checkInfo['error']);
        }
		
	
        $fields    = $request->query->all();
		$isice = isset($fields['isice']) ? $fields['isice'] : 0;
        $fields['userId'] = $currentUser->id;
        $orderInfo = $processor->getOrderInfo($targetId, $fields);
		
		
		
        if (((float) $orderInfo["totalPrice"]) == 0) {
            $formData               = array();
            $formData['userId']     = $currentUser["id"];
            $formData["targetId"]   = $fields["targetId"];
            $formData["targetType"] = $fields["targetType"];
            $formData['amount']     = 0;
            $formData['totalPrice'] = 0;
            $coinSetting            = $this->setting("coin");
            $formData['priceType']  = empty($coinSetting["priceType"]) ? 'RMB' : $coinSetting["priceType"];
            $formData['coinRate']   = empty($coinSetting["coinRate"]) ? 1 : $coinSetting["coinRate"];
            $formData['coinAmount'] = 0;
            $formData['payment']    = 'alipay';
            $order                  = $processor->createOrder($formData, $fields);

            if ($order['status'] == 'paid') {
                return $this->redirect($this->generateUrl($processor->getRouter(), array('id' => $order['targetId'])));
            }
        }

        $couponApp = $this->getAppService()->findInstallApp("Coupon");

        if (isset($couponApp["version"]) && version_compare("1.0.5", $couponApp["version"], "<=")) {
            $orderInfo["showCoupon"] = true;
        }

        $verifiedMobile = '';

        if ((isset($currentUser['verifiedMobile'])) && (strlen($currentUser['verifiedMobile']) > 0)) {
            $verifiedMobile = $currentUser['verifiedMobile'];
        }

        $orderInfo['verifiedMobile'] = $verifiedMobile;
        if(isset($orderInfo['course']['teacherIds'])){
            $arr=$orderInfo['course']['teacherIds'];
             $arr=implode("|",$arr);//将教师ID分割出来
        //var_dump($arr);exit;
        $orderInfo['teacherIds']=$arr;
         $arr=$orderInfo['course']['teacherIds'];

        $arr=implode("|",$arr);//将教师ID分割出来
      
        $orderInfo['teacherIds']=$arr;
        }
		
        $orderInfo['isice']=$isice;
        return $this->render('TopxiaWebBundle:Order:order-create.html.twig', $orderInfo);
    }
	
    public function smsVerificationAction(Request $request)
    {
        $currentUser    = $this->getCurrentUser();
        $verifiedMobile = '';

        if ((isset($currentUser['verifiedMobile'])) && (strlen($currentUser['verifiedMobile']) > 0)) {
            $verifiedMobile = $currentUser['verifiedMobile'];
        }

        return $this->render('TopxiaWebBundle:Order:order-sms-modal.html.twig', array(
            'verifiedMobile' => $verifiedMobile
        ));
    }

    public function createAction(Request $request)
    {
        $fields = $request->request->all();
		$isice = $request->get('isice');
		$isice += 0;
		$fields['isice'] = $isice;
        $mz=$fields['mz'];
		if(empty($mz)){
			  $mz=0;
		}
       $userid=$fields['promo'];//优惠码
        $rmb=$fields['totalPrice'];
        //根据优惠卡【promo】进行查询价格进行判断
        //判断$userid【优惠码】是否大于0
        //*(course.discount/100)
        @$discount=$fields['discount'];
        @$discountid=$fields['discountId'];
        // var_dump($discountid);
        if (isset($fields['coinPayAmount']) && $fields['coinPayAmount'] > 0) {
            $scenario = "sms_user_pay";

            if ($this->setting('cloud_sms.sms_enabled') == '1' && $this->setting("cloud_sms.{$scenario}") == 'on') {
                list($result, $sessionField, $requestField) = SmsToolkit::smsCheck($request, $scenario);
                if (!$result) {
                    return $this->createMessageResponse('error', '短信验证失败。');
                }
            }
        }

        $user = $this->getCurrentUser();
		 
        $fields['userId'] = $user->id;
         //var_dump($fields['userId']);die;
        if (!$user->isLogin()) {
            return $this->createMessageResponse('error', '用户未登录，创建订单失败。');
        }

        if (!array_key_exists("targetId", $fields) || !array_key_exists("targetType", $fields)) {
            return $this->createMessageResponse('error', '订单中没有购买的内容，不能创建!');
        }

        $targetType  = $fields["targetType"];
        $targetId    = $fields["targetId"];
        $maxRate     = $fields["maxRate"];
		 
        $priceType   = "RMB";
        $coinSetting = $this->setting("coin");
        $coinEnabled = isset($coinSetting["coin_enabled"]) && $coinSetting["coin_enabled"];

        if ($coinEnabled && isset($coinSetting["price_type"])) {
            $priceType = $coinSetting["price_type"];
        }

        $cashRate = 1;

        if ($coinEnabled && isset($coinSetting["cash_rate"])) {
            $cashRate = $coinSetting["cash_rate"];
        }
	
        $processor = OrderProcessorFactory::create($targetType);
		
        try {
            if (isset($fields["promo"]) && $fields["promo"] == "请输入优惠码") {
                $fields["promo"] = "";
            }

            list($amount, $totalPrice, $couponResult) = $processor->shouldPayAmount($targetId, $priceType, $cashRate, $coinEnabled, $fields);
    		
        
      			$shouldPayMoney                           = (string) ((float) $fields["shouldPayMoney"]);
				
                if ($discountid != 0 && $fields['isice']==0 ) {
                    //$amount                                  = (string) ((float) $amount);
					
                     $totalPrice                                   = (string) ((float) $totalPrice*($discount/10));
                }
			
                if($mz != 0 ){
					
                    if($mz>$rmb){
                         $amount                                   = (string) ((float) 0);    
						
                    }elseif($mz<$rmb){
						//翟红利---当优惠券金额小于支付金额的时候 
                          $amount                                   = (string) ((float)$amount-$mz);
						  $amount=strval(round($amount,2));
						
						if($amount<0){
							 $amount                                   = (string) ((float) 0);
						}
					
                    }elseif($mz==$rmb){
                          $amount                                   = (string) ((float) 0);
					
                    }else{
                          $amount                                   = (string) ((float) $amount);
						
                    }  
                }
			
            //价格比较
            if (intval($totalPrice * 100) != intval($fields["totalPrice"] * 100)) {
				
                $this->createMessageResponse('error', "实际价格不匹配，不能创建订单!");
            }
            //价格比较
            if (intval($amount * 100) != intval($shouldPayMoney * 100)) {
				
                return $this->createMessageResponse('error', '支付价格不匹配，不能创建订单!');
            }
   			
            //虚拟币抵扣率比较
			
            if (isset($fields['coinPayAmount']) && (intval((float) $fields['coinPayAmount'] * 100) > intval($totalPrice * $maxRate * 100))) {
                return $this->createMessageResponse('error', '虚拟币抵扣超出限定，不能创建订单!');
            }

            if (isset($couponResult["useable"]) && $couponResult["useable"] == "yes") {
                $coupon         = $fields["couponCode"];
                $couponDiscount = $couponResult["decreaseAmount"];
            }
			//判断支付方式
             if(!empty($fields['promo']) and !empty($fields['coinPayAmount'])){
				 //使用优惠券支付+酷币
				 $payment='promo,coin';
			 }elseif(!empty($fields['promo'])){
				 //使用优惠券
				 $payment='promo';
			 }elseif(!empty($fields['card']) and !empty($fields['coinPayAmount'])){
				 //学习卡+酷币
				 $payment='card,coin';
			 }elseif(!empty($fields['card'])){
				 //使用学习卡支付
				 $payment='card';
			 }elseif(!empty($fields['coinPayAmount'])){
				 //使用酷币支付
				 $payment='coin';
			 }else{
				$payment='none'; 
			 }
            $orderFileds = array(
                'promo'         =>$userid,
				'cardId'         =>$fields['card'],
				'cardAmount'     =>empty($fields['cm']) ? '' : $fields['cm'],
                'priceType'      => $priceType,
                'totalPrice'     => $totalPrice,
                'amount'         => $amount,
                'coinRate'       => $cashRate,
                'coinAmount'     => empty($fields["coinPayAmount"]) ? 0 : $fields["coinPayAmount"],
                'userId'         => $user["id"],
                'payment'        => $payment,
                'targetId'       => $targetId,
                'coupon'         => empty($coupon) ? '' : $coupon,
                'couponDiscount' => empty($couponDiscount) ? 0 : $couponDiscount,
				'name'			 =>	empty($fields["name"]) ? '' : $fields["name"],
				'tel'			 =>	empty($fields["tel"]) ? '' : $fields["tel"],
				'address'		 =>	empty($fields["address"]) ? '' : $fields["address"],
				'note'		 	 =>	empty($fields["note"]) ? '' : $fields["note"]
            );
            $order = $processor->createOrder($orderFileds, $fields);
            //曹乾 订单提交成功之后更改学习卡的的状态
            //学习卡的id
             $id = $fields['card'];
                //判断是否使用学习卡
			//var_dump($order['amount']);exit;
            if ($order["status"] == "paid") {
				//修改学习卡状态
				 $cardInfo = $this->getLearningCardService()->selectId($id);
				
                    //判断是否打折
                    if($fields['discountId']!='0'){
                        $money = $fields['totalPrice'];
                        //判断课程的价格与学习卡的价格
                       if($cardInfo['category']=='0' || $cardInfo['category']=='6'){
							$diff = $cardInfo['money']-($money*1);//学习卡0.9
						}else{
							$diff = $cardInfo['money']-$money;
						}
                        if($diff>0){
                            //如何差价大于0 更改学习卡的面额
                            $mresult = $this->getLearningCardService()->updateMoney($id,$diff);
                        }else{
                            //小于等于0的话更改学习卡的状态
                            $diff = 0;
                            $mresult = $this->getLearningCardService()->updateMoney($id,$diff);
                            $res =  $this->getLearningCardService()->upStatus(3,$fields['card']);
                        }
                    }else{
						if($mz>0){
							 $money = $fields['totalPrice']-$mz;
						}else{
							 $money = $fields['totalPrice'];
						}
                      if($cardInfo['category']=='0' || $cardInfo['category']=='6'){
							$diff = $cardInfo['money']-($money*1);//学习卡0.9
						}else{
							$diff = $cardInfo['money']-$money;
						}
						
                        //判断学习卡与课程的差价
                        if($diff>0){
                            //更改学习卡的面额
                            $mresult = $this->getLearningCardService()->updateMoney($id,$diff);       
                        }else{
                            //更改学习卡的状态
                            $diff = 0;
                            $mresult = $this->getLearningCardService()->updateMoney($id,$diff);
                            $res =  $this->getLearningCardService()->upStatus(3,$fields['card']);
                        }
                    }
				//翟红利--订单提交成功，更改优惠码的使用状态
           		 $promo2 = $this->getPromoService()->updatestatus($userid);
                //支付成功，获取课程积分
                $userid=$fields['userId'];//用户ID
                $courseid=$fields['targetId'];//课程ID
                //根据课程ID查询到课程活动的积分
                $course=$this->getCourseService()->getCourse($courseid);
                $courseintegral=$course['integral'];//得到当前课程的活动积分
                $time=date('Y-m-d H:i:s',time());
                $activitiesstarttime=$course['activitiesstarttime'];//活动开始时间
                $activitiesendtime=$course['activitiesendtime'];//活动结束时间
                if($time>$activitiesstarttime and $time<$activitiesendtime){//如果在活动期间内说明打折了，开始赠送
                    //echo "打折中";
                    $usersignin=$this->getUserService()->selectsignin($userid);
                    $userintegral=$usersignin[0]['integral'];//用户当前的积分
                    $integralnum=$courseintegral+$userintegral;//活动的积分+用户当前的积分
                    $integr=$this->getUserService()->updatasignin($userid,$integralnum);
                     $usersignin=$this->getUserService()->selectsignin($userid);
                     $userintegral=$usersignin[0]['integral'];//用户签到之后的总积分
                     //查询指定积分升级的总积分
                     $levelarr= $this->getUserService()->getUserlevel();
                     $userdj= $usersignin[0]['level'];//用户当前等级
                     $bind=array(
                                    'userid' =>$userid,//赠送购买者的ID
                                     'signintime'=>time(),//赠送的时间
                                     'signinintegral'=>$courseintegral,//赠送的积分
                                     'getintegraltype' =>'buy',//赠送类型{购买课程送的}
                                 );
                     $a=$this->getUserService()->addintegral($bind);
                    foreach ($levelarr as $k=>$v){
                        $integral= $v['integral'];//每次遍历一次价格
                        $dj=$v['levelnum'];//每次遍历一次等级 
                         if($integral<=$userintegral){
                             //查询到等级修改用户当前的等级
                             
                             if($userdj<$dj){
                                 $profile = $this->getUserService()->updateUserdj($userid, $dj);
                                 //等级上升
                                 $this->setFlashMessage('success', '恭喜您升级为VIP'.$dj);
                             }
                         }
                
                    }
                }else{
                   // echo "不是打折课程";
                }
                //exit;
				
                return $this->redirect($this->generateUrl($processor->getRouter(), array('id' => $order["targetId"])));
            }else if((float)$order['amount']==0){
			
				//修改优惠券状态
				$promo2 = $this->getPromoService()->updatestatus($userid);
					//修改学习卡状态
				 $cardInfo = $this->getLearningCardService()->selectId($id);
                    //判断是否打折
				
                    if(!empty($fields['discountId'])){
                        $money = $fields['totalPrice'];
                        //判断课程的价格与学习卡的价格
                       if($cardInfo['category']=='0' || $cardInfo['category']=='6'){
							$diff = $cardInfo['money']-($money*1);//学习卡0.9
						}else{
							$diff = $cardInfo['money']-$money;
						}
						
                        if($diff>0){
                            //如何差价大于0 更改学习卡的面额
                            $mresult = $this->getLearningCardService()->updateMoney($id,$diff);
                        }else{
                            //小于等于0的话更改学习卡的状态
                            $diff = 0;
                            $mresult = $this->getLearningCardService()->updateMoney($id,$diff);
                            $res =  $this->getLearningCardService()->upStatus(3,$fields['card']);
                        }
                    }else{
						if($mz>0){
							 $money = $fields['totalPrice']-$mz;
						}else{
							 $money = $fields['totalPrice'];
						}
						
						if($cardInfo['category']=='0' || $cardInfo['category']=='6'){
							$diff = $cardInfo['money']-($money*1);//学习卡0.9
						}else{
							$diff = $cardInfo['money']-$money;
						}
                        
						
                        //判断学习卡与课程的差价
                        if($diff>0){
                            //更改学习卡的面额
                            $mresult = $this->getLearningCardService()->updateMoney($id,$diff);       
                        }else{
                            //更改学习卡的状态
                            $diff = 0;
                            $mresult = $this->getLearningCardService()->updateMoney($id,$diff);
                            $res =  $this->getLearningCardService()->upStatus(3,$fields['card']);
                        }
                    }
			}
			//var_dump($order);exit;
            return $this->redirect($this->generateUrl('pay_center_show', array(
                'sn' => $order['sn']
            )));
        } catch (\Exception $e) {
            return $this->createMessageResponse('error', $e->getMessage());
        }
    }

    public function detailAction(Request $request, $id)
    {
        $order = $this->getOrderService()->getOrder($id);
		if(!empty($order["promo"])){
			$promo = $this->getPromoService()->getMyPromo($order["promo"]);
			$order['mz']=$promo[0]['mz'];
		}
		
        $user = $this->getUserService()->getUser($order['userId']);

        $orderLogs = $this->getOrderService()->findOrderLogs($order['id']);

        $users = $this->getUserService()->findUsersByIds(ArrayToolkit::column($orderLogs, 'userId'));

        return $this->render('TopxiaWebBundle:Order:detail-modal.html.twig', array(
            'order'     => $order,
			'mz'=>empty($order['mz'])?0.00:$order['mz'],
            'user'      => $user,
            'orderLogs' => $orderLogs,
            'users'     => $users
        ));
    }

    public function couponCheckAction(Request $request, $type, $id)
    {
        if ($request->getMethod() == 'POST') {
            $code = $request->request->get('code');
            
            if (!in_array($type, array('course', 'vip', 'classroom'))) {
                throw new \RuntimeException('优惠码不支持的购买项目。');
            }
            $promo = $this->getPromoService()->getMyPromo($code);
            if(!isset($promo)){
                $promo=array(
                    '0'=>0,
                    'promo'=>$code
                );
            }else{
              $promo=array(
                'id'=>$promo[0]['id'],
                'promo'=>$promo[0]['promo'],
                'mz'=>$promo[0]['mz'],
                'yxq'=>$promo[0]['yxqtime'],
                'status'=>$promo[0]['status']  
                );
            }    
//            $couponInfo = $this->getCouponService()->checkCouponUseable($code, $type, $id, $price);
            return $this->createJsonResponse($promo);
        }
    }
    
     protected function getUserService()
    {
        return $this->getServiceKernel()->createService('User.UserService');
    }

    protected function getAppService()
    {
        return $this->getServiceKernel()->createService('CloudPlatform.AppService');
    }

    protected function getCashService()
    {
        return $this->getServiceKernel()->createService('Cash.CashService');
    }

    protected function getOrderService()
    {
        return $this->getServiceKernel()->createService('Order.OrderService');
    }

    protected function getCouponService()
    {
        return $this->getServiceKernel()->createService('Coupon:Coupon.CouponService');
    }

    protected function getVipService()
    {
        return $this->getServiceKernel()->createService('Vip:Vip.VipService');
    }

    protected function getCourseService()
    {
        return $this->getServiceKernel()->createService('Course.CourseService');
    }

    private function getClassroomService()
    {
        return $this->getServiceKernel()->createService('Classroom:Classroom.ClassroomService');
    }
     protected function getPromoService()
    {
        return $this->getServiceKernel()->createService('kuke.PromoService');
    }

    //caoqian
     protected function getLearningCardService()
    {
        return $this->getServiceKernel()->createService('Kuke.LearningCardService');
    }
}
